import { getEnv } from '@/store';
import qs from 'qs';

/**
 * 统一获取不同类型的值，将函数调用后变成普通值统一输出
 * @param {any} value 获取值，如果是函数则调用，否则直接输出
 * @param  {...any} args 如果是函数值，这里是需要传入的参数
 * @returns {Promise<any>} 
 */
export const waitResult = (value, ...args) => {
    return new Promise((resolve) => {
        if (typeof value === 'function') {
            resolve(value(...args));
        } else {
            resolve(value);
        }
    });
}


export const humpTo = (str, char = '_') => {
    let temp = str.replace(/[A-Z]/g, function (match) {
        return char + match.toLowerCase();
    });

    if (temp.slice(0, 1) === char) {
        temp = temp.slice(1);
    }

    return temp;
}

export const underlineToHump = (str) => {
    // 如果首字母是下划线，先去掉
    if (str.slice(0, 1) === '_') {
        str = str.slice(1);
    }

    return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
        return $1 + $2.toUpperCase();
    });
}

export const getRouteLink = (name, query) => {
    let url = getEnv().NODE_ENV === 'development' ? `./${name}.html` : getEnv().ENTRY + '_' + name;

    if (query) {
        url += '?' + qs.stringify(query);
    }

    return url;
};

export const routeTo = (name, query, target = '_self') => {
    window.open(getRouteLink(name, query), target);
}

export const isVueComponent = (target) => {
    return (
        target &&
        // 检查基础类型
        (typeof target === 'object' || typeof target === 'function') &&
        (
            // Vue 3 组件标识
            target.__isVue === true ||
            // 检查组件特征属性
            'setup' in target ||
            'render' in target ||
            // 函数式组件检查
            (typeof target === 'function' && target.name === 'renderFnWithContext')
        )
    );
}

export const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);

export const createBlankForm = (options) => {
    const form = document.createElement('form');
    form.method = options.method;
    form.target = '_blank';
    form.action = options.url;

    const appendItem = function(query, key = '') {
        for (let name in query) {
            let value = query[name];
            const input = document.createElement('input');
            let direct = false;

            if (/^\@/.test(name)) {
                direct = true;
                name = name.substr(1);
            }

            input.type = 'hidden';
            input.name = key === '' ? name : `${key}[${name}]`;

            if (direct) {
                // Filelist 是类数组，转为真正数组
                if (util.type(value) == 'file') {
                    value = util.like2Array(value);
                }

                appendItem(value, input.name);
            } else {
                if (util.type(value) == 'file') {
                    input.type = 'file';
                }

                input.value = value;
                form.appendChild(input);
            }
        }
    };

    appendItem(requestParams(options.params));

    return new Promise((resolve, reject) => {
        resolve({
            form,
            run: () => {
                document.body.appendChild(form);
                form.submit();
                setTimeout(function() {
                    document.body.removeChild(form);
                }, 1000);
    
                return form;
            }
        });
    });
};

export const pw = (promise) => {
    return promise
        .then(result => [null, result])
        .catch(error => {
            console.warn(error);

            return [error, null];
        });
};
